package initialize

import (
	"encoding/json"
	"fmt"
	"github.com/nacos-group/nacos-sdk-go/clients"
	"github.com/nacos-group/nacos-sdk-go/common/constant"
	"github.com/nacos-group/nacos-sdk-go/vo"
	"github.com/spf13/viper"
	"go.uber.org/zap"
	"shop/user-srv/global"
)

func GetEnvInfo(env string) bool {
	viper.AutomaticEnv()
	return viper.GetBool(env)
}

func InitConfig() {

	configFileName := "user-srv/config-debug.yaml"
	vip := viper.New()
	vip.SetConfigFile(configFileName)
	if err := vip.ReadInConfig(); err != nil {
		panic("Fatal error config file: " + err.Error())
	}

	_ = vip.Unmarshal(&global.NocasConfig)
	fmt.Println(global.NocasConfig, "global.NocasConfig")
	//server config
	serverConfigs := []constant.ServerConfig{
		{
			IpAddr:      global.NocasConfig.IpAddress,
			ContextPath: global.NocasConfig.ContextPath,
			Port:        global.NocasConfig.Port,
			Scheme:      global.NocasConfig.Scheme,
		},
	}

	//client config
	clientConfig := constant.ClientConfig{
		NamespaceId:         global.NocasConfig.NamespaceId, // 如果需要支持多namespace，我们可以创建多个client,它们有不同的NamespaceId。当namespace是public时，此处填空字符串。
		TimeoutMs:           global.NocasConfig.TimeoutMs,
		NotLoadCacheAtStart: global.NocasConfig.NotLoadCacheAtStart,
		LogDir:              global.NocasConfig.LogDir,
		CacheDir:            global.NocasConfig.CacheDir,
		LogLevel:            global.NocasConfig.LogLevel,
	}

	// 创建动态配置客户端
	client, err := clients.CreateConfigClient(map[string]interface{}{
		"serverConfigs": serverConfigs,
		"clientConfig":  clientConfig,
	})
	if err != nil {
		panic(err)
	}
	content, err := client.GetConfig(vo.ConfigParam{
		DataId: global.NocasConfig.DataId,
		Group:  global.NocasConfig.Group})
	if err != nil {
		panic(err)
	}

	err = json.Unmarshal([]byte(content), &global.ServerConfig)
	fmt.Println(global.ServerConfig, "global.ServerConfig")
	if err != nil {
		zap.S().Fatalf("Unable to parse server config")
	}

	////读取配置文件
	//configFileName := "user-srv/config-debug.yaml"
	//vip := viper.New()
	//vip.SetConfigFile(configFileName)
	//if err := vip.ReadInConfig(); err != nil {
	//	panic("Fatal error config file: " + err.Error())
	//}
	//
	//fmt.Println(global.ServerConfig, "global.ServerConfig")
	//_ = vip.Unmarshal(&global.ServerConfig)
	////if err != nil {
	////	panic("Fatal error server config: " + err.Error())}
	////}
	//zap.S().Infof("配置信息1 %v", global.ServerConfig)
	//vip.WatchConfig()
	//vip.OnConfigChange(func(e fsnotify.Event) {
	//	fmt.Println("config file changed:", e.Name)
	//	zap.S().Infof("配置产生变化 %v", global.ServerConfig)
	//	_ = viper.ReadInConfig()
	//	_ = viper.Unmarshal(global.ServerConfig)
	//	zap.S().Infof("配置信息 %v", global.ServerConfig)
	//})
}
